package utils;

import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import cliente.pagina.contenido.ContenidoCorreo;

public class ThreadCorreo extends Thread {

   int[] res=new int[2];
   String host;
   String user;
   String pass;
   private ThreadControl control;

   public int[] getMails()
   {
     return res;
   }

    public ThreadCorreo(String str) {
        super(str);
    }

    public int[] getCantidadMailsNoLeidos(String host,String user,String pass)
       throws Exception {
      try
      {
     int[] cantidad=new int[2];

     Properties props = System.getProperties();
     props.put("imap", host);

     Session session = Session.getDefaultInstance(props, null);

     Store store = session.getStore("imap");
     store.connect(host, user, pass);

     System.out.println("Leyendo correo. Usuario="+user);

     // Obtiene la carpeta
     Folder folder = store.getFolder("INBOX");
     folder.open(Folder.READ_ONLY);

     cantidad[0]=folder.getNewMessageCount();
     cantidad[1]=folder.getUnreadMessageCount();

     // Cierra la  conexion
     folder.close(false);
     store.close();
     return cantidad;
      }
      catch(Exception e2)
      {
        throw e2;
      }
   }


    public void run()
    {
    	
      long actual =   System.currentTimeMillis();
      long fin = actual + 10000;
      //corre 18 segundos y para si o si
      int count=0;
      while (actual<fin)
      {
         //System.out.println(getName()+" tratando de leer el correo. "+host+"  --  "+user+"  --  "+pass);

         res[0]=-1;
         try
        {
         res =  this.getCantidadMailsNoLeidos(host,user,pass);
         Thread.currentThread().sleep(500);
        }
         catch(Exception e)
        {
        //e.printStackTrace();
        }

         //System.out.println("Resultado de lectura de correo "+res[0]+"  --  "+res[1]);
         if(res[0]>=0)
         {
           System.out.println("Leyo mails, parando thread");
           this.control.setPara("S");
           //PruebaMain.para="S";
           this.stop();
         }
         actual=System.currentTimeMillis();
         count++;
      }
       System.out.println("Termina thread " + getName());
      
    }
  public void setUser(String user) {
    this.user = user;
  }
  public void setPass(String pass) {
    this.pass = pass;
  }
  public void setHost(String host) {
    this.host = host;
  }
  public void setControl(ThreadControl control) {
    this.control = control;
  }

}

